package com.service.impl;

import com.dao.OrderDao;
import com.dao.impl.OrderDaoImpl;
import com.pojo.CartItem;
import com.pojo.Order;
import com.pojo.TbOrder;
import com.pojo.TbOrderList;
import com.service.OderService;

import java.util.List;
import java.util.UUID;

public class OderServiceImpl implements OderService {

    private OrderDao orderDao=new OrderDaoImpl();

    @Override
    public Order createOrder(List<CartItem> cartItemList, String aid) {
        if(cartItemList != null && cartItemList.size() > 0){
            String oid = UUID.randomUUID().toString().replaceAll("-", "");
            //计算总价
            long total = cartItemList.stream().mapToLong(CartItem::getTotalPrice).sum();//整个订单的总价
            Long uid = cartItemList.get(0).getUid();//获取到用户的 id
            orderDao.addOrder(oid, uid, total, aid);//插入到订单表

            cartItemList.forEach(cartItem -> {
                //将每一个商品关联到当前的订单中
                long id = cartItem.getId();//kzid
                long totalPrice = cartItem.getTotalPrice();//当前商品的总价
                int num = cartItem.getNum();//获取数量
                orderDao.addOrderDetail(oid, id, num, totalPrice);
            });

            Order order = new Order();
            order.setMoney(total);
            order.setId(oid);
            return order;

        }
        return null;
    }

    @Override
    public void processPay(String id) {

        //这个订单如果是未支付状态才可以更新为已支付
        String status = orderDao.findStatusById(id);
        if ("0".equalsIgnoreCase(status)) {
            //才可以支付
            orderDao.updateStaus2Success(id);
        }else {
            System.err.println("当前订单状态异常,无法更新为支付状态");
        }
    }

    @Override
    public void cancelOrder(String id) {
        orderDao.cancelOrder(id);
    }

    @Override
    public List<TbOrder> findAllOrder(Long uid) {
        return orderDao.findAllOrder(uid);
    }


}